<?php
/*
Aurus CMS - free OOP CMS
Copyright (C) 2010  Nestor Yanchuk

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
if (! defined('ROOT')) die();

/**
 * Клас для передачі файлів між сервером та користувачем
 * 
 * @package Aurus
 * @author Kvis
 * @copyright 2010
 * @version 1.0
 * @access public
 */

class FilesTransfer implements Core {
	/**
	 * Return an instance of class
	 *
	 * @return FilesTransfer
	 */
	public static function getInstance(){
		return Factory::get(__CLASS__);
	}
	/**
	 * Функція віддає файл користувачу
	 *
	 * @param string $filename - шлях до файлу
	 * @param string $maxSpeed - максимальна швидкість завантаження (kb/s), 0 - без обмеження
	 * @return boolean, true - Ok, false - failed
	 */
	static function fileDownload($filename,$maxSpeed = 0){
		if (!$filename or !is_file($filename)) {
			return false;
		}
		ob_implicit_flush();
		@ini_set("max_execution_time",0);
		@set_time_limit(0);

		$fsize = filesize($filename);
		$ftime = date("D, d M Y H:i:s T", filemtime($filename));
		$range = 0;

		$handle = @fopen($filename, "rb");
		if (!$handle){
			header ("HTTP/1.0 403 Forbidden");
			exit;
		}

		$filename = end(explode('/',$filename));

		if (isset($_SERVER["HTTP_RANGE"])) {
			$range = $_SERVER["HTTP_RANGE"];
			$range = str_replace("bytes=", "", $range);
			$range = str_replace("-", "", $range);
			if ($range) {
				fseek($handle, $range);
			}
		}

		if ($range) {
			header("HTTP/1.1 206 Partial Content");
		} else {
			header("HTTP/1.1 200 OK");
		}

		header("Content-Disposition: attachment; filename=\"{$filename}\"");
		header("Last-Modified: {$ftime}");
		header("Content-Length: ".($fsize-$range));
		header("Accept-Ranges: bytes");
		header("Content-Range: bytes {$range}-".($fsize - 1)."/".$fsize);
		header("Content-Disposition: attachment; filename=".$filename);

		if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
			header('Content-Type: application/force-download');
		} else {
			header('Content-Type: application/octet-stream');
		}

		@ob_end_clean();
		session_write_close();

		if (($speed = $maxSpeed) > 0) {
			$sleep_time = (8 / $maxSpeed) * 1e6;
		} else {
			$sleep_time = 0;
		}

		while(!feof($handle)) {
			print fread($handle,1024 * 8);
			ob_flush();
			flush();
			usleep($sleep_time);
		}

		fclose($handle);
		return true;
	}
	function fileDownloadFromContent($name , $content){
		ob_implicit_flush();
		@ini_set("max_execution_time",0);
		@set_time_limit(0);

		$fsize = strlen($content);
		$ftime = date("D, d M Y H:i:s T", TIME);
		$range = 0;


		if (!$content){
			header ("HTTP/1.0 403 Forbidden");
			exit;
		}

		header("Content-Disposition: attachment; filename=\"{$name}\"");
		header("Last-Modified: {$ftime}");
		header("Content-Length: ".$fsize);
		header("Accept-Ranges: bytes");
		header("Content-Disposition: attachment; filename=".$name);

		if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
			header('Content-Type: application/force-download');
		} else {
			header('Content-Type: application/octet-stream');
		}

		@ob_end_clean();
		session_write_close();

		print $content;
		ob_flush();
		flush();

		return true;
	}
}